########
# What does this do?
#######
rm(list=ls())

# load libraries
packs = c('tidyverse', 'hrbrthemes', "here")
source("r/LoadPkg.R")
loadPkg(packs)

# read data
covars = read_csv(here('repFile', 'data', 'covars_final.csv'))


# lo-hi comparison
lohi = 
  covars %>% 
  filter(rearing_agg %in% c(1, 4)) %>% 
  mutate(hi = ifelse(rearing_agg == 4, 1, 0))

pDat =
  lohi %>% 
  dplyr::select(`NSE income category` = nse, Age = age_factor, 
                `Prior voter` = voted_5_years_num, 
                `Victim` = victim_num, 
                `Woman` = woman, 
                hi) %>%
  drop_na() %>% 
  gather(key = 'demographic', value = 'value', -hi) %>% 
  group_by(hi, demographic, value) %>% 
  tally() %>% 
  group_by(hi, demographic) %>% 
  mutate(total = sum(n), 
         pct = n/total)

# clean up variable values
pDat$value = str_replace_all(pDat$value, pattern = '0', replacement = 'No')
pDat$value = str_replace_all(pDat$value, pattern = '^[1]$', replacement = 'Yes')
pDat$value = str_replace_all(pDat$value, pattern = 'Estrato', 
                             replacement = '')
pDat$value[pDat$value == "No aplica (Sin estratificación)"] <- "NA"
pDat$value = str_replace_all(pDat$value, pattern = 'De', 
                             replacement = '')
pDat$value = str_replace_all(pDat$value, pattern = 'años', 
                             replacement = '')
pDat$value = str_replace_all(pDat$value, pattern = 'Más de', 
                             replacement = '')
pDat$value = str_replace_all(pDat$value, pattern = " a ", 
                             replacement = '-')

# plot demographics
ggplot(data = pDat, aes(x = value, y = pct, fill = factor(hi))) + 
  geom_col(position = position_dodge(width = .5)) + 
  facet_wrap(vars(demographic), scales = 'free') + 
  theme_ipsum_rc(grid = 'Y') + 
  theme(legend.position = 'top') + 
  labs(x = "", y = "Proportion of respondents", 
       fill = "Child-rearing scale:") + 
  scale_fill_manual(values = c("black", "grey"), 
                    breaks = c(0, 1), 
                    labels = c('Low (1/4)', 'High (4/4)'))

ggsave(here("repFile", "paper", "figures", "auth-demo.pdf"), 
       device = cairo_pdf)
ggsave(here("repFile", "JOP submission", "auth-demo.eps"), 
       device = cairo_ps)
ggsave(here("repFile", "JOP submission", "auth-demo.pdf"), 
       device = cairo_pdf)

